/**
 *    Copyright 2006-2017 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.mybatis.generator.utils;

import org.mybatis.generator.api.ConnectionFactory;
import org.mybatis.generator.config.Context;

import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class JdbcUtil {

    // 表示定义数据库的用户名  
    private static String USERNAME;

    // 定义数据库的密码  
    private static String PASSWORD;

    // 定义数据库的驱动信息  
    private static String DRIVER;

    // 定义访问数据库的地址  
    private static String URL;

    // 定义数据库的链接  
    private Connection connection = null;

    // 定义sql语句的执行对象  
    private PreparedStatement pstmt;

    // 定义查询返回的结果集合  
    private ResultSet resultSet;

//    static{
//        //加载数据库配置信息，并给相关的属性赋值
//        loadConfig();
//    }

    /**
     * 加载数据库配置信息，并给相关的属性赋值
     */
//    public static void loadConfig() {
//        try {
//            InputStream inStream = JdbcUtil.class
//                    .getResourceAsStream("/jdbc.properties");
//            Properties prop = new Properties();
//            prop.load(inStream);
//            USERNAME = prop.getProperty("jdbc.username");
//            PASSWORD = prop.getProperty("jdbc.password");
//            DRIVER= prop.getProperty("jdbc.driver");
//            URL = prop.getProperty("jdbc.url");
//        } catch (Exception e) {
//            throw new RuntimeException("读取数据库配置文件异常！", e);
//        }
//    }
    public JdbcUtil(Context context) throws Exception {
        DRIVER = context.getJdbcConnectionConfiguration().getDriverClass();
        URL = context.getJdbcConnectionConfiguration().getConnectionURL();
        USERNAME = context.getJdbcConnectionConfiguration().getUserId();
        PASSWORD = context.getJdbcConnectionConfiguration().getPassword();
        connection = context.getConnection();
    }

    /**
     * 获取数据库连接
     *
     * @return 数据库连接
     */
//    public Connection getConnection(String driver, String url, String username, String password) {
//        try {
//            Class.forName(driver); // 注册驱动
//            connection = DriverManager.getConnection(url, username, password); // 获取连接
//        } catch (Exception e) {
//            throw new RuntimeException("get connection error!", e);
//        }
//        return connection;
//    }

    /**
     * 执行更新操作
     *
     * @param sql    sql语句
     * @param params 执行参数
     * @return 执行结果
     * @throws SQLException
     */
    public boolean updateByPreparedStatement(String sql, List<?> params)
            throws SQLException {
        boolean flag = false;
        int result = -1;// 表示当用户执行添加删除和修改的时候所影响数据库的行数  
        pstmt = connection.prepareStatement(sql);
        int index = 1;
        // 填充sql语句中的占位符  
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        result = pstmt.executeUpdate();
        flag = result > 0 ? true : false;
        return flag;
    }

    /**
     * 执行查询操作
     *
     * @param sql    sql语句
     * @param params 执行参数
     * @return
     * @throws SQLException
     */
    public List<Map<String, Object>> findResult(String sql, List<?> params)
            throws SQLException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            list.add(map);
        }
        return list;
    }

    /**
     * 释放资源
     */
    public void releaseConn() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public List<String> getTablesOfDb() throws Exception {
        List<String> tables = new ArrayList<String>();
        try {
            DatabaseMetaData dbMetaData = connection.getMetaData();
            String[] types = {"TABLE"};
            ResultSet tabs = dbMetaData.getTables(null, null, null, types/*只要表就好了*/);

            while (tabs.next()) {
                //只要表名这一列
                tables.add(tabs.getObject("TABLE_NAME").toString());
            }
        } catch (Exception e) {
            throw e;
        }

        return tables;
    }

    public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String username = "root";
        String password = "123456";
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
//        JdbcUtil jdbcUtil = new JdbcUtil(driver, url, username, password);


//        try {
//
//            DatabaseMetaData dbMetaData = connection.getMetaData();
//
//            //可为:"TABLE",   "VIEW",   "SYSTEM   TABLE",
//            //"GLOBAL   TEMPORARY",   "LOCAL   TEMPORARY",   "ALIAS",   "SYNONYM"
//            String[] types = {"TABLE"};
//
//            List<String> tables = new ArrayList<String>();
//
//            ResultSet tabs = dbMetaData.getTables(null, null, null, types/*只要表就好了*/);
//
//            while (tabs.next()) {
//                //只要表名这一列
//                tables.add(tabs.getObject("TABLE_NAME").toString());
//
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        } finally {
//            jdbcUtil.releaseConn();
//        }
    }
}  